﻿using CopyBaron.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace CopyBaron.ProcessList.WindowActivator
{
    public static class WindowActivator
    {
        public static bool ActivatePreviousWindow()
        {
            var windows = new Windows();
            var visibleWindows = windows.lstWindows
                                        .Where(w => w.winVisible)
                                        .OrderBy(w => w.winZOrder)
                                        .ToList();

            var thisWindowHandle = Process.GetCurrentProcess().MainWindowHandle;
            var thisWindow = visibleWindows.Single(w => w.winHandle == thisWindowHandle);

            var thisWindowIndex = visibleWindows.IndexOf(thisWindow);
            if (visibleWindows.Count <= thisWindowIndex)
            {
                return false;
            }

            var previousWindow = visibleWindows[thisWindowIndex + 1];
            if (previousWindow.winPlacement.showCmd == Declarations.ShowWindowCommands.Hide)
            {
                return false;
            }

            previousWindow.PushToForeground();
            return true;
        }
    }
}
